//
//  LoginViewController.m
//  AoJi
//
//  Created by IMacLife on 15/1/22.
//  Copyright (c) 2015年 xuanheng. All rights reserved.
//

#import "LoginViewController.h"
#import "RegistViewController.h"
#import "SettingViewController.h"
#import "PersonalViewController.h"

#import "YHNetwork.h"
#import <ShareSDK/ShareSDK.h>

#define buttonWidth (self.view.frame.size.width-200)/3
#define labelWidth self.view.frame.size.width/3
@interface LoginViewController ()

@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBarHidden=YES;
    
    
//    [[UIApplication sharedApplication]setStatusBarStyle:UIStatusBarStyleDefault];
    self.view.backgroundColor=[UIColor colorWithRed:236.0f/255.0f green:236.0f/255.0f blue:236.0f/255.0f alpha:1.0f];
    

    
    //设置nav
    UIView *titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 64)];
    titleView.backgroundColor=[UIColor colorWithRed:246.0f/255.0f green:246.0f/255.0f blue:246.0f/255.0f alpha:1.0f];
    
    UIButton *back = [UIButton buttonWithType:UIButtonTypeCustom];
    back.frame=CGRectMake(0, 20, 44, 44);
    [back setImage:[UIImage imageNamed:@"fanhuihui"] forState:UIControlStateNormal];
    [back addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    [titleView addSubview:back];
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-50, 30, 100, 30)];
    title.text=@"登录";
    title.font=[UIFont systemFontOfSize:18];
    title.textAlignment=NSTextAlignmentCenter;
    [titleView addSubview:title];
    
    [self.view addSubview:titleView];
    

    //文本框
    userName = [[UITextField alloc]initWithFrame:CGRectMake(13, 90, self.view.frame.size.width-26, 44)];
    userName.borderStyle=UITextFieldViewModeAlways;
    userName.placeholder=@"请输入用户名";
    userName.delegate=self;
    //设置左边图片,和出现模式
    UIImageView *userimg = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"yonghuming"]];
    userName.leftView=userimg;
    userName.leftViewMode=UITextFieldViewModeAlways;
    [self.view addSubview:userName];
    
    password = [[UITextField alloc]initWithFrame:CGRectMake(13, 155, self.view.frame.size.width-26, 44)];
    password.borderStyle=UITextFieldViewModeAlways;
    password.placeholder=@"请输入密码";
    password.secureTextEntry=YES;
    password.delegate=self;
    
    UIImageView *passwordleft = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mima"]];
    password.leftView=passwordleft;
    password.leftViewMode=UITextFieldViewModeAlways;
    
//    UIImageView *passwordright = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"more"]];
//    password.rightView=passwordright;
//    password.rightViewMode=UITextFieldViewModeAlways;
    //眼睛
    UIButton *right = [UIButton buttonWithType:UIButtonTypeCustom];
    right.frame=CGRectMake(0, 0, 40, 40);
    [right setImage:[UIImage imageNamed:@"xianshiyinc"] forState:UIControlStateNormal];
    [right addTarget:self action:@selector(password) forControlEvents:UIControlEventTouchUpInside];
    password.rightView=right;
    password.rightViewMode=UITextFieldViewModeAlways;
    
    
    [self.view addSubview:password];
    
    //下次自动登录
    checkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    checkBtn.frame=CGRectMake(13, CGRectGetMaxY(password.frame)+14, 20, 20);
    checkBtn.selected=NO;
    [checkBtn setImage:[UIImage imageNamed:@"weixuan"] forState:UIControlStateNormal];
    [checkBtn setImage:[UIImage imageNamed:@"yixuan"] forState:UIControlStateSelected];
    [checkBtn addTarget:self action:@selector(CheckBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:checkBtn];
    
    UILabel *loginlabel = [[UILabel alloc]initWithFrame:CGRectMake(40, CGRectGetMaxY(password.frame)+15, 200, 20)];
    loginlabel.text=@"下次自动登录";
    loginlabel.font=[UIFont systemFontOfSize:15];
    loginlabel.textColor=[Color colorFromHexRGB:@"7f7f7f"];
    [self.view addSubview:loginlabel];
    
    //登录
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    loginBtn.frame = CGRectMake(13, CGRectGetMaxY(checkBtn.frame)+16, self.view.frame.size.width-26, 44);
    loginBtn.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"but"]];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    loginBtn.titleLabel.font=[UIFont systemFontOfSize:15];
    [loginBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [loginBtn addTarget:self action:@selector(LoginBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    
//    UIView *lineleft = [[UIView alloc]initWithFrame:CGRectMake(13, CGRectGetMaxY(loginBtn.frame)+35, self.view.frame.size.width/2-88, 1)];
//    lineleft.backgroundColor=[UIColor colorWithRed:130.0f/255.0f green:130.0f/255.0f blue:130.0f/255.0f alpha:1.0f];
//    [self.view addSubview:lineleft];
//    
//    UILabel *otherlogin = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-60, CGRectGetMaxY(loginBtn.frame)+20, 120, 30)];
//    otherlogin.text=@"其他方式登录";
//    [self.view addSubview:otherlogin];
//    
//    UIView *lineRight = [[UIView alloc]initWithFrame:CGRectMake(CGRectGetMaxX(otherlogin.frame), CGRectGetMaxY(loginBtn.frame)+35, self.view.frame.size.width/2-74, 1)];
//    lineRight.backgroundColor=[UIColor colorWithRed:130.0f/255.0f green:130.0f/255.0f blue:130.0f/255.0f alpha:1.0f];
//    [self.view addSubview:lineRight];
//    
//    //三方登录
//    UIButton * weixin = [UIButton buttonWithType:UIButtonTypeCustom];
//    weixin.frame=CGRectMake(30, CGRectGetMaxY(otherlogin.frame)+27, buttonWidth, 50);
//    [weixin setImage:[UIImage imageNamed:@"weix"] forState:UIControlStateNormal];
//    [weixin addTarget:self action:@selector(weixinLogin) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:weixin];
//    
//    UILabel *weixinlabel = [[UILabel alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(weixin.frame)+13, labelWidth, 30)];
//    weixinlabel.text=@"微信";
//    weixinlabel.textAlignment=NSTextAlignmentCenter;
//    weixinlabel.font=[UIFont systemFontOfSize:12];
//    [self.view addSubview:weixinlabel];
//    
//    
//    UIButton *qq = [UIButton buttonWithType:UIButtonTypeCustom];
//    qq.frame=CGRectMake(CGRectGetMaxX(weixin.frame)+70, CGRectGetMaxY(otherlogin.frame)+27, buttonWidth, 50);
//    [qq setImage:[UIImage imageNamed:@"qq"] forState:UIControlStateNormal];
//    [qq addTarget:self action:@selector(qqLogin) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:qq];
//    
//    UILabel *qqlabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(weixinlabel.frame), CGRectGetMaxY(qq.frame)+13, labelWidth, 30)];
//    qqlabel.text=@"腾讯QQ";
//    qqlabel.textAlignment=NSTextAlignmentCenter;
//    qqlabel.font=[UIFont systemFontOfSize:12];
//    [self.view addSubview:qqlabel];
//    
//    
//   
//    //腾讯微博,下线
////    UIButton *tencent = [UIButton buttonWithType:UIButtonTypeCustom];
////    tencent.frame=CGRectMake(CGRectGetMaxX(weixin.frame)+39, CGRectGetMaxY(otherlogin.frame)+27, buttonWidth, 50);
////    [tencent setImage:[UIImage imageNamed:@"tencent"] forState:UIControlStateNormal];
////    [tencent addTarget:self action:@selector(tencentLogin) forControlEvents:UIControlEventTouchUpInside];
////    [self.view addSubview:tencent];
////    
////    UILabel *tencentlabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(weixinlabel.frame), CGRectGetMaxY(tencent.frame)+13, labelWidth, 30)];
////    tencentlabel.text=@"腾讯微博";
////    tencentlabel.textAlignment=NSTextAlignmentCenter;
////    tencentlabel.font=[UIFont systemFontOfSize:12];
////    [self.view addSubview:tencentlabel];
//    
//    UIButton *sina = [UIButton buttonWithType:UIButtonTypeCustom];
//    sina.frame=CGRectMake(CGRectGetMaxX(qq.frame)+65, CGRectGetMaxY(otherlogin.frame)+27, buttonWidth, 50);
//    [sina setImage:[UIImage imageNamed:@"xinlang"] forState:UIControlStateNormal];
//    [sina addTarget:self action:@selector(sinaLogin) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:sina];
//    
//    UILabel *sinalabel = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(qqlabel.frame), CGRectGetMaxY(sina.frame)+13, labelWidth, 30)];
//    sinalabel.text=@"新浪微博";
//    sinalabel.textAlignment=NSTextAlignmentCenter;
//    sinalabel.font=[UIFont systemFontOfSize:12];
//    [self.view addSubview:sinalabel];
    
    
    //注册
    UIButton *registBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    registBtn.frame = CGRectMake(13, self.view.frame.size.height-74, self.view.frame.size.width-26, 44);
    registBtn.backgroundColor=[UIColor colorWithPatternImage:[UIImage imageNamed:@"but2"]];
    [registBtn setTitle:@"没有澳际账号?现在去注册" forState:UIControlStateNormal];
    registBtn.titleLabel.font=[UIFont systemFontOfSize:17];
    [registBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [registBtn addTarget:self action:@selector(RegistBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registBtn];
    
    
    
}

#pragma mark -----------action
//返回
-(void)back
{
//    [self.drawer open];
    [self dismissViewControllerAnimated:YES completion:nil];
    
//    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - ICSDrawerController

- (void)drawerControllerWillOpen:(ICSDrawerController *)drawerController
{
    self.view.userInteractionEnabled = NO;
}

- (void)drawerControllerWillClose:(ICSDrawerController *)drawerController
{
    self.view.userInteractionEnabled = YES;
}


//显示密码
-(void)password
{
    password.secureTextEntry=!password.secureTextEntry;
}

#pragma mark --------------登录
//下次自动登录
-(void)CheckBtn
{
    checkBtn.selected=!checkBtn.selected;
    [kUserDefaults setBool:checkBtn.selected forKey:kAutoLogin];
    [kUserDefaults synchronize];
}

//登录按钮
-(void)LoginBtn
{
    NSLog(@"登录");
    if ([userName.text isEqualToString:@""]) {
        UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入用户名" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertview show];
    }else
        if ([password.text isEqualToString:@""]) {
        UIAlertView *alertview = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请输入密码" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alertview show];
        }
    [self requestLogin];
}

//接口/user/login     http://cent.dsgrd.com/user/login
-(void)requestLogin
{
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"username"] = userName.text;
    params[@"password"] = password.text;
    
    [YHNetwork getInformationWithReguestType:RequestTypePost WithParameters:params WithApi:@"user/login" WhenSuccess:^(NSMutableDictionary *response) {
        NSLog(@"%@",response);
        dict=response;
        [self requestLoginData];
        
    } WhenFailure:^(NSError *failure) {
        NSLog(@"%@",failure.localizedDescription);
    }];
    
    
}

-(void)requestLoginData
{
    int i = [dict[@"code"]intValue];
    if (i == 0) {
        NSLog(@"登录成功");
        
        
        PersonalViewController *personalVC = [[PersonalViewController alloc]init];
//        [self.navigationController popToViewController:personalVC animated:YES];
//       ;
//        [self.navigationController pushViewController:personalVC animated:YES];
       
//        [self presentViewController:personalVC animated:YES completion:nil];
        
        //NSuserdefaults为null会报错，循环替换为空字符串
        NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:dict[@"data"]];
        for (NSString *key in newDict.allKeys) {
            if ([newDict[key] isKindOfClass:[NSNull class]]) {
                newDict[key]=@"";
            }
        }
        
        
        [[NSUserDefaults standardUserDefaults]setObject:@"yes" forKey:@"login"];
        
        //保存数据
        [[NSUserDefaults standardUserDefaults]setObject:newDict[@"access_token"] forKey:kAccessToken];
    
        [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%@ %@",newDict[@"area1"],newDict[@"area2"]] forKey:kAddress];
        
        [[NSUserDefaults standardUserDefaults]setObject:newDict[@"auth_key"] forKey:kAuthKey];
        [[NSUserDefaults standardUserDefaults]setObject:newDict[@"avatar"] forKey:kAvatar];
        [[NSUserDefaults standardUserDefaults]setObject:newDict[@"cellphone"] forKey:kMobile];
        [[NSUserDefaults standardUserDefaults]setObject:newDict[@"created_at"] forKey:kRegisterDate];
        [[NSUserDefaults standardUserDefaults]setObject:newDict[@"email"] forKey:kEmail];
        [[NSUserDefaults standardUserDefaults]setObject:newDict[@"id"] forKey:kID];
        [[NSUserDefaults standardUserDefaults]setObject:newDict[@"last_login_ip"] forKey:kLastLoginIP];
//        [[NSUserDefaults standardUserDefaults]setObject:newDict[@"link_data"][@"webid"] forKey:@"webid"];
        [[NSUserDefaults standardUserDefaults]setObject:newDict[@"nickname"] forKey:kNickName];
        [[NSUserDefaults standardUserDefaults]setObject:newDict[@"role"] forKey:kRole];
        [[NSUserDefaults standardUserDefaults]setObject:newDict[@"source"] forKey:kSource];
        [[NSUserDefaults standardUserDefaults]setObject:newDict[@"updated_at"] forKey:kUpdatedat];
        [[NSUserDefaults standardUserDefaults]setObject:newDict[@"username"] forKey:kUserName];
//        [[NSUserDefaults standardUserDefaults]synchronize];
        
        

        
        
        //数据
//        NSLog(@"%@",dict[@"data"][@"access_token"]);           //token
//        NSLog(@"%@",dict[@"data"][@"area1"]);                  //省份
//        NSLog(@"%@",dict[@"data"][@"area2"]);                  //城市
//        NSLog(@"%@",dict[@"data"][@"auth_key"]);               //空
//        NSLog(@"%@",dict[@"data"][@"avatar"]);                 //空字符串
//        NSLog(@"%@",dict[@"data"][@"cellphone"]);              //电话
//        NSLog(@"%@",dict[@"data"][@"created_at"]);             //
//        NSLog(@"%@",dict[@"data"][@"email"]);                  //
//        NSLog(@"%@",dict[@"data"][@"id"]);                     //
//        NSLog(@"%@",dict[@"data"][@"last_login_ip"]);          //
//        NSLog(@"%@",dict[@"data"][@"last_login_time"]);        //
//        NSLog(@"%@",dict[@"data"][@"link_data"][@"webid"]);    //
//        NSLog(@"%@",dict[@"data"][@"nickname"]);               //
//        NSLog(@"%@",dict[@"data"][@"role"]);                   //
//        NSLog(@"%@",dict[@"data"][@"source"]);                 //
//        NSLog(@"%@",dict[@"data"][@"updated_at"]);             //
//        NSLog(@"%@",dict[@"data"][@"username"]);               //用户名
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"loginsuccess" object:personalVC];
        [self dismissViewControllerAnimated:YES completion:^{
            
            
            //            [self.drawer replaceCenterViewControllerWithViewController:personalVC];
            
        }];
        
    }else if(i == 1)
    {
        UIAlertView *_alertView = [[UIAlertView alloc]initWithTitle:@"提示" message:@"用户名或者密码不正确" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [_alertView show];
         [[NSUserDefaults standardUserDefaults]setObject:@"no" forKey:@"login"];
    }
}


//三方登录
-(void)qqLogin
{
    NSLog(@"qq登录");
}

-(void)weixinLogin
{
    NSLog(@"weixin登录");
}

//腾讯微博
//-(void)tencentLogin
//{
//    NSLog(@"tencent登录");
//}

-(void)sinaLogin
{
   NSLog(@"sina登录");
}



//注册按钮
-(void)RegistBtn
{
    NSLog(@"笨蛋");
    RegistViewController *registVC = [[RegistViewController alloc]init];
    [self.navigationController pushViewController:registVC animated:YES];
    [self presentViewController:registVC animated:YES completion:nil];
}

#pragma mark 收键盘
//收起键盘
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [userName resignFirstResponder];
    [password resignFirstResponder];
    return YES;
}

//点击空白地方收起键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [userName resignFirstResponder];
    [password resignFirstResponder];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
